﻿<template>
  <div class="app-container">
    <div class="filter-title">
      <el-form label-position="right" label-width="80px">
        <el-form-item :label="$t('admin.username')+' :'">
          <el-input
            v-model="listQuery.username"
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('admin.username')"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('admin.email')+' :'">
          <el-input
            v-model="listQuery.email"
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('admin.email')"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-button
          style="margin-left: 20px"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >{{ $t('table.search') }}</el-button>
        <el-button
          v-if="permission.authorize"
          style="margin-left: 10px; float:right"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >{{ $t('table.add') }}</el-button>
        <el-button
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          @click="handleRefresh"
        >{{ $t('table.refresh') }}</el-button>
      </el-form>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255,255,255,0.2)"
      border
      fit
      highlight-current-row
      style="width: 100%min-height:1000px"
    >
      <el-table-column fixed="left" align="center" :label="$t('table.id')" width="65">
        <template slot-scope="scope">
          <span>{{ (listQuery.page-1)*listQuery.limit+scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('admin.username')">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('admin.operation')">
        <template slot-scope="scope">
          <span>{{ scope.row.itoc_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('admin.email')">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('public.createTime')">
        <template slot-scope="scope">
          <span>{{ scope.row.createtime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('admin.type')">
        <template slot-scope="scope">
          <span>{{ operationsTypeEs(scope.row.region_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('admin.status')">
        <template slot-scope="scope">
          <span :class="statusColor(scope.row.status)">{{ disableEs(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        :label="$t('weChat.particular')"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="!(typeof (scope.row.wx)==='object' && scope.row.wx.constructor===Array)"
            type="primary"
            size="mini"
            @click="handleUntied(scope.row)"
          >{{ $t('weChat.untied') }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        :label="$t('table.actions')"
        :width="operWidth"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleRead(scope.row)"
          >{{ $t('table.read') }}</el-button>
          <el-button
            v-if="permission.update"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >{{ $t('table.edit') }}</el-button>
          <el-button
            v-if="permission.authorize && scope.row.id !== id"
            type="primary"
            size="mini"
            @click="handleAuthorize(scope.row)"
          >{{ $t('table.authorize') }}</el-button>
          <el-button
            v-if="permission.del && scope.row.id !== id"
            size="mini"
            type="danger"
            @click="handleModifyStatus(scope.row,'deleted')"
          >{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 编辑 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="35%"
        style="width: 400px margin-left:120px"
        size="small"
      >
        <el-form-item :label="$t('admin.username')+' :'" prop="username">
          <el-input v-if="dialogStatus=='create'" v-model="temp.username"></el-input>
          <span v-else>{{ temp.username }}</span>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus=='create'"
          :label="$t('admin.password')+' :'"
          prop="password"
        >
          <el-input v-model="temp.password" type="password"></el-input>
        </el-form-item>
        <el-form-item :label="$t('admin.email')+' :'" prop="email">
          <el-input v-model="temp.email"></el-input>
        </el-form-item>
        <el-form-item :label="$t('admin.operation')+' :'" prop="itoc_id">
          <select-page
            v-if="dialogStatus=='create'"
            :id="temp.itoc_id"
            :name="temp.itoc_name"
            style="width:200px"
            placeholder="请选择区域"
            key-field="id"
            show-field="name"
            :data="operationOptions"
            :count="operationCount"
            :page-size="pageSize"
            @getList="getOperationList"
            @values="getOperationid"
          ></select-page>
          <span v-else>{{ temp.itoc_name }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          :disabled="!createDisabled"
          @click="createData"
        >{{ $t('table.confirm') }}</el-button>
        <el-button
          v-else
          type="primary"
          :disabled="!updateDisabled"
          @click="updateData"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormRead">
      <el-form
        :model="temp"
        label-position="right"
        label-width="40%"
        style="width: 400px margin-left:120px"
        size="small"
      >
        <el-form-item :label="$t('admin.username')+' :'">
          <span>{{ temp.username }}</span>
        </el-form-item>
        <el-form-item :label="$t('admin.email')+' :'">
          <span>{{ temp.email }}</span>
        </el-form-item>
        <el-form-item :label="$t('admin.operation')+' :'">
          <span>{{ temp.itoc_name }}</span>
        </el-form-item>
        <el-form-item :label="$t('admin.status')+' :'">
          <span>{{ disableEs(temp.status) }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限菜单 -->
    <el-dialog
      v-loading="permissionLoading"
      title="权限"
      :visible.sync="permissionVisible"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255,255,255,0.2)"
    >
      <el-tree
        ref="tree"
        :data="dataPermission"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="initial"
        :expand-on-click-node="false"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="changgeAuth">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-loading="untiedLoading"
      title="解绑"
      :visible.sync="untiedVisible"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255,255,255,0.2)"
    >
      <div style="text-align:center">
        <div class="message">
          <div class="avatar">
            <img :src="wx.headimg" />
          </div>
          <div class="nickname">
            <span>{{ wx.nickname }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="untiedVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="changgeUntied">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import selectPage from "@/views/select/SelectPage"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
  name: "Admin",
  components: {
    "select-page": selectPage
  },
  data() {
    const username = (rule, value, callback) => {
      // return false
      if (value && value.length > 0) {
        var reg = /^[A-Za-z]{1}[A-Za-z0-9_-]{3,15}$/; /* 以字母开头，只能包含字母数字下划线，4到16位 */
        if (reg.test(value)) {
          callback();
        } else {
          callback(
            new Error("以字母开头，只能包含字母数字下划线，字符长度4到16位")
          );
        }
      } else {
        callback(new Error("请填用户名"));
      }
    };
    const password = (rule, value, callback) => {
      // return false
      if (value && value.length > 0) {
        var reg = /^[A-Za-z0-9_]{6,16}$/; /* 只能包含字母数字下划线，字符长度6到16位 */
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("只能包含字母数字下划线，字符长度6到16位"));
        }
      } else {
        callback(new Error("请填写密码"));
      }
    };
    const email = (rule, value, callback) => {
      // return false
      if (value && value.length > 0) {
        var reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/; /* 邮箱规则 */
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请填写正确的邮箱"));
        }
      } else {
        callback(new Error("请填写邮箱"));
      }
    };
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      id: "",
      statusOptions: [
        {
          value: 1,
          label: "正常"
        },
        {
          value: 2,
          label: "禁用"
        }
      ],
      typeOptions: [
        {
          value: 0,
          label: "平台总部"
        },
        {
          value: 1,
          label: "省级运营中心"
        },
        {
          value: 2,
          label: "市级运营中心"
        },
        {
          value: 3,
          label: "区级运营中心"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        username: "",
        nickname: "",
        email: ""
      },
      promissItem: [],
      temp: {
        id: undefined,
        username: "",
        password: "",
        email: "",
        itoc_id: "",
        itoc_name: "",
        status: ""
      },
      wx: {},
      dialogFormVisible: false,
      permissionVisible: false,
      untiedVisible: false,
      untiedLoading: false,
      dialogFormRead: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        username: [{ required: true, trigger: "blur", validator: username }],
        nickname: [{ required: true, message: "请填写昵称", trigger: "blur" }],
        password: [{ required: true, trigger: "blur", validator: password }],
        email: [{ required: true, trigger: "blur", validator: email }],
        itoc_id: [
          { required: true, message: "请选择运营中心", trigger: "blur" }
        ],
        status: [{ required: true, message: "请审核", trigger: "change" }]
      },
      createDisabled: true,
      updateDisabled: true,
      loading: false,
      operationOptions: [],
      operationCount: undefined,
      pageSize: 20,
      dataPermission: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      permissionLoading: false,
      initial: [],
      initpro: [],
      permission: {
        add: false,
        del: false,
        update: false,
        authorize: false
      }
    };
  },
  computed: {
    operWidth: function() {
      let itemCount = 1;
      if (this.permission.del) {
        itemCount += 1;
      }
      if (this.permission.update) {
        itemCount += 1;
      }
      if (this.permission.authorize) {
        itemCount += 1;
      }
      return itemCount * 80 + "px";
    }
  },
  created() {
    
    if (this.$store.state.permission.jurisdiction === "*") {
      this.permission.add = true;
      this.permission.del = true;
      this.permission.update = true;
      this.permission.authorize = true;
    } else {
      const jurisdiction = this.$store.state.permission.jurisdiction.split(",");
      jurisdiction.forEach(element => {
        const id = parseInt(element);
        if (id === 180) {
          this.permission.add = true;
        } else if (id === 181) {
          this.permission.del = true;
        } else if (id === 182) {
          this.permission.update = true;
        } else if (id === 179) {
          this.permission.authorize = true;
        }
      });
    }
    this.id = JSON.parse(getToken()).id;
    this.getList();
  },
  methods: {
    getOperationList(pageNumber = 1, search = "") {
      this.getOperation(pageNumber, search);
    },
    getOperationid(data) {
      if (data.length > 0) {
        this.temp.itoc_id = data[0].id;
        this.temp.itoc_name = data[0].name;
      } else {
        this.temp.itoc_id = undefined;
        this.temp.itoc_name = "";
      }
    },
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page
      };
      if (this.listQuery.username) {
        data["username"] = this.listQuery.username;
      }
      if (this.listQuery.email) {
        data["email"] = this.listQuery.email;
      }
      const adminIndexPath = {
        // 获取操作员档案列表
        company: "STQ",
        api: "pc_admin_index",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(adminIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该操作员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const adminDeletePath = {
            company: "STQ",
            api: "pc_admin_deleteAdmin",
            version: "1.0",
            data: {
              id: row.id
            }
          };
          this.socketApi.sendSock(JSON.stringify(adminDeletePath), res => {
            if (res) {
              this.socketData(res);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        pid: "",
        name: "",
        linkman: "",
        linkman_mobile: "",
        region_id: "",
        region_name: "",
        region_type: "",
        status: ""
      };
    },
    resetArea() {
      this.areaOptions = [];
      this.temp.region_id = "";
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        username: "",
        nickname: "",
        email: ""
      };
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      // 添加操作员档案
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            const data = {
              username: this.temp.username,
              password: this.temp.password,
              email: this.temp.email,
              itoc_id: this.temp.itoc_id,
              itoc_name: this.temp.itoc_name
            };
            const addAdminPath = {
              company: "STQ",
              api: "pc_admin_addAdmin",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(addAdminPath), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    handleUpdate(row) {
      // 打开编辑弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.temp.status = parseInt(this.temp.status); // 转成int类型
      this.dialogStatus = "edit";
      this.dialogFormVisible = true;
      this.getOperation();
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleRead(row) {
      // 打开查看弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "read";
      this.dialogFormRead = true;
    },
    updateData() {
      // 更新操作员档案
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = {
              id: this.temp.id,
              email: this.temp.email
            };
            const adminEditPath = {
              company: "STQ",
              api: "pc_admin_editAdmin",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(adminEditPath), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    getPermission(data) {
      const permissionMaps = [];
      data.forEach(result => {
        const permissionObjects = {};
        permissionObjects.id = result.id;
        permissionObjects.label = result.title;
        if (result.children) {
          permissionObjects.children = this.getPermission(result.children);
        }
        permissionMaps.push(permissionObjects);
      });
      return permissionMaps;
    },
    getListChild(data) {
      data.forEach(result => {
        if (result.children) {
          this.getListChild(result.children);
        } else {
          this.initpro.push(result.id);
        }
      });
    },
    // 管理员授权列表
    handleAuthorize(row) {
      this.initpro = [];
      this.initial = [];
      this.temp = Object.assign({}, row);
      this.permissionVisible = true;
      const adminAuthPath = {
        company: "STQ",
        api: "pc_admin_auth",
        version: "1.0",
        data: {
          type: 1,
          id: row.id
        }
      };
      this.socketApi.sendSock(JSON.stringify(adminAuthPath), res => {
        if (res) {
          this.socketData(res);
        } else {
          this.$message.error(" 更新失败 ");
        }
        setTimeout(() => {
          this.updateDisabled = true;
        }, 1000);
      });
    },
    // 微信解绑
    handleUntied(row) {
      this.wx = Object.assign({}, row.wx); // copy obj
      this.wx.pid = row.id;
      this.untiedVisible = true;
    },
    changgeUntied() {
      const adminCancelPath = {
        company: "STQ",
        api: "pc_admin_cancel",
        version: "1.0",
        data: {
          id: this.wx.pid,
          openid: this.wx.openid
        }
      };
      this.socketApi.sendSock(JSON.stringify(adminCancelPath), res => {
        this.socketData(res);
      });
    },
    changgeAuth() {
      const promissItem = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys())
        .join(",");
      const adminAuthPath = {
        company: "STQ",
        api: "pc_admin_auth",
        version: "1.0",
        data: {
          type: 2,
          id: this.temp.id,
          rule: promissItem
        }
      };
      this.socketApi.sendSock(JSON.stringify(adminAuthPath), res => {
        if (res !== '{"type":"ping"}') {
          const resj = JSON.parse(res);
          if (resj.code === -1) {
            this.$message.error(resj.message);
          } else {
            this.permissionVisible = false;
            this.$notify({
              title: "成功",
              message: "授权成功",
              type: "success",
              duration: 2000
            });
          }
        }
        this.listLoading = false;
      });
    },
    // 运营中心选择
    getOperation(pageNumber, search) {
      const industryIndexPath = {
        company: "STQ",
        api: "pc_itoc_getList",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(industryIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
          this.listLoading = false;
        } else {
          if (resj.api === "pc_itoc_getList") {
            this.operationOptions = resj.data;
            this.operationCount = resj.count;
          } else if (resj.api === "pc_admin_editAdmin") {
            // 运营中心管理员状态更改
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_admin_index") {
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (resj.api === "pc_admin_deleteAdmin") {
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } else if (resj.api === "pc_admin_addAdmin") {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_admin_auth") {
            this.dataPermission = this.getPermission(resj.data.menu);
            this.getListChild(resj.data.menu);
            const initmenu = resj.data.rule[0].rules.split(",");
            initmenu.forEach(res => {
              const resNew = parseInt(res);
              if (this.initpro.indexOf(resNew) !== -1) {
                this.initial.push(resNew);
              }
            });
          } else if (resj.api === "pc_admin_cancel") {
            this.untiedVisible = false;
            this.$notify({
              title: "成功",
              message: "解绑成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.message {
  display: table;
  margin: auto;
}
.message div {
  padding: 0 5px;
  display: table-cell;
  vertical-align: middle;
}
.message .nickname {
  min-width: 100px;
}
.message .avatar img {
  width: 80px;
  border-radius: 40px;
}
.message .close i {
  cursor: pointer;
}
</style>
